<template>
  <div class="login-container">
    <el-card class="login-card">
      <div slot="header">
        <span>{{ isLogin ? '登录' : '注册' }}</span>
      </div>
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input type="password" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item v-if="!isLogin" prop="nickname" label="昵称">
          <el-input v-model="form.nickname"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">
            {{ isLogin ? '登录' : '注册' }}
          </el-button>
          <el-button @click="toggleMode">
            切换到{{ isLogin ? '注册' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    return {
      isLogin: true,
      form: {
        username: '',
        password: '',
        nickname: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    toggleMode() {
      this.isLogin = !this.isLogin
      this.$refs.form.resetFields()
    },
    async handleSubmit() {
      try {
        const valid = await this.$refs.form.validate()
        if (valid) {
          if (this.isLogin) {
            const res = await this.$http.post('/user/login', {
              username: this.form.username,
              password: this.form.password
            })
            if (res.data) {
              localStorage.setItem('token', res.data.token)
              localStorage.setItem('user', JSON.stringify(res.data.user))
              this.$message.success('登录成功')
              this.$router.push('/')
            }
          } else {
            const res = await this.$http.post('/user/register', {
              username: this.form.username,
              password: this.form.password,
              nickname: this.form.nickname
            })
            if (res.data) {
              this.$message.success('注册成功，请登录')
              this.isLogin = true
              this.$refs.form.resetFields()
            }
          }
        }
      } catch (error) {
        console.error('Error:', error)
        const errorMsg = error.response?.data?.error || '操作失败'
        this.$message.error(errorMsg)
      }
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.login-card {
  width: 400px;
}
</style> 